package com.xin.di.uav.applet.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.xin.di.uav.applet.mapper.NewUserMapper;
import com.xin.di.uav.common.request.CarrierWaybillRequest;
import com.xin.di.uav.common.request.CreateWaybillRequest;
import com.xin.di.uav.common.utils.FyUtils;
import com.xin.di.uav.po.OrderMapper;
import com.xin.di.uav.applet.mapper.ServiceAreaMapper;
import com.xin.di.uav.applet.request.ServiceAreaEditParam;
import com.xin.di.uav.applet.resp.OrderResp;
import com.xin.di.uav.applet.service.OrderService;
import com.xin.di.uav.common.enums.RescueOrderStatusEnum;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.request.common.IdRequest;
import com.xin.di.uav.common.request.order.PlaceOrderRequest;
import com.xin.di.uav.common.response.IdAndNameResp;
import com.xin.di.uav.common.utils.BeanUtil;
import com.xin.di.uav.mapper.OrderCommodityMapper;
import com.xin.di.uav.mapper.ScenicSpotMapper;
import com.xin.di.uav.operate.mapper.MerchantMapper;
import com.xin.di.uav.operate.mapper.PlacementPointMapper;
import com.xin.di.uav.operate.po.PlacementPoint;
import com.xin.di.uav.operate.po.ServiceAreaPO;
import com.xin.di.uav.operate.rest.IntraCityRest;
import com.xin.di.uav.po.OrderCommodity;
import com.xin.di.uav.po.ScenicSpot;
import com.xin.di.uav.user.order.po.OrderPO;
import com.xin.di.uav.user.po.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IntraCityRest intraCityRest;
    @Autowired
    private NewUserMapper newUserMapper;

    @Autowired
    private ServiceAreaMapper serviceAreaMapper;

    @Autowired
    private OrderCommodityMapper orderCommodityMapper;
    @Autowired
    private PlacementPointMapper placementPointMapper;
    @Autowired
    private FyUtils fyUtils;

    @Autowired
    private ScenicSpotMapper scenicSpotMapper;


    @Override
    public boolean delete(String id) {
        return false;
    }

    @Override
    public boolean update(ServiceAreaEditParam serviceArea) {
        return false;
    }

    @Override
    public int updateStatus(IdRequest idRequest) {
        Integer status = idRequest.getStatus();
        if (status == null) {
            throw new BusinessException("状态不能为空");
        }
        String name = RescueOrderStatusEnum.getName(status);
        if (name == null) {
            throw new BusinessException("非法状态");
        }
        OrderPO orderPO = orderMapper.selectById(idRequest.getId());
        if (ObjectUtil.isEmpty(orderPO)) {
            throw new BusinessException("订单记录不存在");
        }
        Integer oldStatus = orderPO.getStatus();
        if (status.equals(oldStatus)) {
            throw new BusinessException("当前订单已是该状态");
        }
        orderPO.setStatus(status);
        if (RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus().equals(status)) {
            String fyCode = this.sendOrder(orderPO);
            orderPO.setFyOrderNo(fyCode);
        }
        return orderMapper.updateStatus(orderPO);
    }

    //    @Async
    public String sendOrder(OrderPO orderPO) {
        String placementPointId = orderPO.getPlacementPointId();
        PlacementPoint placementPoint = placementPointMapper.selectById(placementPointId);
        if (placementPoint == null) {
            throw new BusinessException("投放点不存在");
        }
        String scenicSpotId = placementPoint.getScenicSpotId();
        ScenicSpot scenicSpot = scenicSpotMapper.selectById(scenicSpotId);
        if (scenicSpot == null) {
            throw new BusinessException("服务区不存在");
        }
        CarrierWaybillRequest carrierWaybillRequest = new CarrierWaybillRequest();
        carrierWaybillRequest.setGpsType(1);
        carrierWaybillRequest.setGoodsType(1);
        carrierWaybillRequest.setGoodsWeight(10);
        carrierWaybillRequest.setReceiverLat(placementPoint.getLatitude().toString());
        carrierWaybillRequest.setReceiverLon(placementPoint.getLongitude().toString());
        carrierWaybillRequest.setSenderLon(placementPoint.getSenderLongitude().toString());
        carrierWaybillRequest.setSenderLat(placementPoint.getSenderLatitude().toString());
        JSONObject jsonObject1 = fyUtils.carrierWaybill(carrierWaybillRequest);
        System.out.println(jsonObject1);
        CreateWaybillRequest createWaybillRequest = new CreateWaybillRequest();
        String takeoffCode = jsonObject1.getJSONObject("obj").getString("takeoffCode");
        String landingCode = jsonObject1.getJSONObject("obj").getString("landingCode");
        createWaybillRequest.setSenderCode(takeoffCode);
        createWaybillRequest.setReceiverCode(landingCode);


        createWaybillRequest.setSenderTel(placementPoint.getSenderTel());
        createWaybillRequest.setSenderAddr(placementPoint.getSenderAddr());
        createWaybillRequest.setSenderName(placementPoint.getSenderName());


        createWaybillRequest.setAmount(orderPO.getTotalAmount().doubleValue());
        createWaybillRequest.setPushTime(String.valueOf(new Date().getTime()));
        createWaybillRequest.setReceiverTel(orderPO.getPayPhone());
        createWaybillRequest.setReceiverName(orderPO.getReceiveName());
        createWaybillRequest.setReceiverAddr(scenicSpot.getAddress());

        return fyUtils.createWaybill(createWaybillRequest);
    }

    @Override
    public ServiceAreaPO getById(String id) {
        return null;
    }

    @Override
    public OrderResp list(int pageNum, int pageSize, String orderNo, String payPhone) {
        OrderResp orderResp = new OrderResp();
        pageNum = (pageNum - 1) * pageSize;
        int cnt = orderMapper.count(orderNo, payPhone);
        if (cnt > 0) {
            List<OrderPO> orderPOS = orderMapper.selectList(pageNum, pageSize, orderNo, payPhone);
            List<String> userIds = orderPOS.stream().map(OrderPO::getUserId).collect(Collectors.toList());
            List<UserPO> userPOS = newUserMapper.selectByIds(userIds);
            List<String> scenicSpotIds = orderPOS.stream().map(OrderPO::getServiceArea).toList();
            List<IdAndNameResp> idAndNameRespList = serviceAreaMapper.selectIdAndName(scenicSpotIds);
            List<OrderResp.Record> records = new ArrayList<>();
            List<String> orderSns = orderPOS.stream().map(OrderPO::getOrderNo).toList();
            List<OrderCommodity> orderCommodities = orderCommodityMapper.selectById(orderSns);

            for (OrderPO orderPO : orderPOS) {
                OrderResp.Record record = BeanUtil.copyProperties(orderPO, OrderResp.Record.class);
                for (IdAndNameResp idAndNameResp : idAndNameRespList) {
                    if (idAndNameResp.getId().equals(orderPO.getServiceArea())) {
                        record.setServiceArea(idAndNameResp.getName());
                    }
                }
                for (UserPO userPO : userPOS) {
                    if (orderPO.getUserId().equals(userPO.getId())) {
                        record.setPayPhone(userPO.getPhone());
                    }

                }
                List<OrderCommodity> orderCommodities1 = orderCommodities.stream().filter(orderCommodity -> orderCommodity.getOrderSn().equals(orderPO.getOrderNo())).toList();
                if (CollectionUtil.isNotEmpty(orderCommodities1)) {
                    List<OrderResp.OrderCommodityResp> orderCommodityRespList = BeanUtil.copyProperties(orderCommodities1, OrderResp.OrderCommodityResp.class);
                    record.setOrderCommodityRespList(orderCommodityRespList);
                }

                records.add(record);
            }


            orderResp.setRecordList(records);

        }
        orderResp.setTotal(cnt);

        return orderResp;
    }
}
